import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import '../../providers/auth_provider.dart';
import '../../providers/offline_mode_provider.dart';
import '../../widgets/platform/adaptive_card.dart';
import '../../widgets/platform/adaptive_button.dart';
import '../../../core/offline/offline_data_manager.dart';
import '../../../core/offline/offline_mode_manager.dart'
    as offline_mode_manager;
import '../../../core/offline/offline_mode_manager.dart' show OfflineModeStatus;
import '../../../domain/entities/user.dart';

/// 用户设置页面
class UserSettingsPage extends ConsumerWidget {
  const UserSettingsPage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final currentUser = ref.watch(currentUserProvider);
    final offlineModeStatus = ref.watch(offlineModeStatusProvider);
    final connectivityStatus = ref.watch(connectivityStatusProvider);

    return Scaffold(
      appBar: AppBar(
        title: const SelectableText('用户设置'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => context.pop(),
        ),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 用户信息卡片
            _buildUserInfoCard(context, currentUser),
            const SizedBox(height: 24),

            // 网络模式状态卡片
            _buildNetworkModeCard(
                context, ref, offlineModeStatus, connectivityStatus),
            const SizedBox(height: 24),

            // 离线操作按钮
            _buildOfflineOperationButtons(context, ref),
            const SizedBox(height: 24),

            // 账户操作
            _buildAccountActions(context, ref),
          ],
        ),
      ),
    );
  }

  /// 构建用户信息卡片
  Widget _buildUserInfoCard(BuildContext context, User? user) {
    return AdaptiveCard(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SelectableText(
            '个人信息',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 16),
          if (user != null) ...[
            ListTile(
              leading: CircleAvatar(
                radius: 24,
                backgroundColor: Theme.of(context).primaryColor,
                child: SelectableText(
                  user.username.substring(0, 1).toUpperCase(),
                  style: const TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              title: SelectableText(user.username),
              subtitle: SelectableText(user.email),
            ),
            const Divider(),
            ListTile(
              leading: const Icon(Icons.security),
              title: const SelectableText('角色'),
              subtitle: SelectableText(_getRoleDisplayName(user.role)),
            ),
            if (user.orgName != null)
              ListTile(
                leading: const Icon(Icons.account_balance),
                title: const SelectableText('组织'),
                subtitle: SelectableText(user.orgName!),
              ),
          ] else
            const Center(
              child: SelectableText('未获取到用户信息'),
            ),
        ],
      ),
    );
  }

  /// 构建网络模式状态卡片
  Widget _buildNetworkModeCard(
    BuildContext context,
    WidgetRef ref,
    AsyncValue<OfflineModeStatus> offlineModeStatus,
    AsyncValue<ConnectivityResult> connectivityStatus,
  ) {
    return AdaptiveCard(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SelectableText(
            '网络模式状态',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 16),
          _buildStatusRow('连接状态', _connectivityStatusText(connectivityStatus)),
          _buildStatusRow('离线模式', _offlineModeStatusText(offlineModeStatus)),
          const SizedBox(height: 16),
          Row(
            children: [
              Expanded(
                child: ElevatedButton(
                  onPressed: () {
                    ref
                        .read(offlineModeNotifierProvider.notifier)
                        .forceOffline();
                  },
                  child: const Text('强制离线'),
                ),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: ElevatedButton(
                  onPressed: () {
                    ref
                        .read(offlineModeNotifierProvider.notifier)
                        .forceOnline();
                  },
                  child: const Text('强制在线'),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建离线操作按钮
  Widget _buildOfflineOperationButtons(BuildContext context, WidgetRef ref) {
    return AdaptiveCard(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SelectableText(
            '离线操作',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 16),
          AdaptiveButton(
            onPressed: () async {
              final offlineDataManager = OfflineDataManager();
              await offlineDataManager.clearAllOperations();
              if (context.mounted) {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('离线操作记录已清空')),
                );
              }
            },
            child: const Text('清空离线操作记录'),
          ),
          const SizedBox(height: 16),
          AdaptiveButton(
            onPressed: () async {
              final offlineDataManager = OfflineDataManager();
              final operations =
                  await offlineDataManager.getOfflineOperations();
              final count = operations.length;
              if (context.mounted) {
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('待同步操作数: $count')),
                );
              }
            },
            child: const Text('查看待同步操作数'),
          ),
          const SizedBox(height: 16),
          AdaptiveButton(
            onPressed: () async {
              // 手动同步用户信息
              try {
                await ref.read(authStateProvider.notifier).syncUserInfo();
                if (context.mounted) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('用户信息同步成功')),
                  );
                }
              } catch (e) {
                if (context.mounted) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('用户信息同步失败: $e')),
                  );
                }
              }
            },
            child: const Text('手动同步用户信息'),
          ),
          const SizedBox(height: 16),
          AdaptiveButton(
            onPressed: () async {
              // 手动同步所有数据
              try {
                final offlineModeManager =
                    ref.read(offline_mode_manager.offlineModeManagerProvider);
                await offlineModeManager.manualSync();
                if (context.mounted) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('数据同步已启动')),
                  );
                }
              } catch (e) {
                if (context.mounted) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('数据同步启动失败: $e')),
                  );
                }
              }
            },
            child: const Text('手动同步所有数据'),
          ),
        ],
      ),
    );
  }

  /// 构建账户操作
  Widget _buildAccountActions(BuildContext context, WidgetRef ref) {
    return AdaptiveCard(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SelectableText(
            '账户操作',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 16),
          AdaptiveButton(
            onPressed: () => _handleLogout(context, ref),
            isPrimary: false,
            child: const Text(
              '退出登录',
              style: TextStyle(color: Colors.red),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建状态行
  Widget _buildStatusRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4.0),
      child: Row(
        children: [
          SelectableText('$label: ',
              style: const TextStyle(fontWeight: FontWeight.w500)),
          SelectableText(value),
        ],
      ),
    );
  }

  /// 获取角色显示名称
  String _getRoleDisplayName(String role) {
    switch (role) {
      case 'ADMIN':
        return '系统管理员';
      case 'DEVELOPER':
        return '开发人员';
      case 'DEMANDER':
        return '需求方';
      case 'TESTER':
        return '测试人员';
      case 'DBA':
        return '数据库管理员';
      default:
        return role;
    }
  }

  /// 获取网络连接状态文本
  String _connectivityStatusText(AsyncValue<ConnectivityResult> status) {
    if (status is AsyncData<ConnectivityResult>) {
      switch (status.value) {
        case ConnectivityResult.wifi:
          return 'WiFi';
        case ConnectivityResult.mobile:
          return '移动数据';
        case ConnectivityResult.none:
          return '无连接';
        default:
          return '未知';
      }
    }
    return '加载中...';
  }

  /// 获取离线模式状态文本
  String _offlineModeStatusText(AsyncValue<OfflineModeStatus> status) {
    if (status is AsyncData<OfflineModeStatus>) {
      switch (status.value) {
        case OfflineModeStatus.online:
          return '在线模式';
        case OfflineModeStatus.offline:
          return '离线模式';
        case OfflineModeStatus.syncing:
          return '同步中...';
      }
    }
    return '加载中...';
  }

  /// 处理退出登录
  void _handleLogout(BuildContext context, WidgetRef ref) {
    showDialog<void>(
      context: context,
      builder: (context) => AlertDialog(
        title: const SelectableText('确认退出'),
        content: const SelectableText('您确定要退出登录吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const SelectableText('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.of(context).pop();
              // 询问用户是否保留本地认证数据以支持离线登录
              _showKeepLocalDataDialog(context, ref);
            },
            child: const SelectableText('确认'),
          ),
        ],
      ),
    );
  }

  /// 显示保留本地数据对话框
  void _showKeepLocalDataDialog(BuildContext context, WidgetRef ref) {
    showDialog<void>(
      context: context,
      builder: (context) => AlertDialog(
        title: const SelectableText('登出选项'),
        content: const SelectableText(
            '请选择登出方式：\n\n- 保留本地数据：仅登出服务器账户，保留本地认证信息以支持离线登录\n- 清除所有数据：完全清除认证信息，包括本地数据'),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              // 保留本地数据，仅登出服务器账户
              ref.read(authStateProvider.notifier).logout();
              context.go('/login');
            },
            child: const SelectableText('保留本地数据'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.of(context).pop();
              // 清除所有数据
              ref.read(authStateProvider.notifier).logout(clearLocalData: true);
              context.go('/login');
            },
            child: const SelectableText('清除所有数据'),
          ),
        ],
      ),
    );
  }
}
